﻿using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class CommentController : Controller
    {
        private readonly IRepository<Comment, int> _commentiReposiory;
        private readonly IRepository<Product, int> _productiReposiory;
        public CommentController(IRepository<Comment,int> commentiReposiory,IRepository<Product,int> productiReposiory)
        {
            _commentiReposiory = commentiReposiory;
            _productiReposiory= productiReposiory;
        }
        #region 留言的列表，查询，删除
        /// <summary>
        /// 留言表的列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var comment = await _commentiReposiory.GetAllListAsync();
            var pro = await _productiReposiory.GetAllListAsync();
            ViewBag.Pro = pro;
            return View(comment);
        }
        [HttpPost]
        public async Task<IActionResult> Index(int page, int limit,string content)
        {
            //var comment = await _commentiReposiory.GetAllListAsync();
            //var query = comment.Where(x => true);
            var news = _commentiReposiory.GetAll();
            var query = news.Include("Product").Where(x => true);
            if (!string.IsNullOrEmpty(content))
            {
                query = query.Where(x => x.Content.Contains(content));
            }
             var count=query.Count();
            var list = query.OrderBy(x => x.Id).Skip((page - 1) * limit).Take(limit).ToList()
               .Select(x => new
               {
                   id = x.Id,
                   name = x.Name,
                   createTime = x.CreateTime.ToString(),
                   content = x.Content,
                   product = x.Product.Title

               });
            return Json(new { Code = 0, Msg = "", Data = list, Count = count });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Del(int id)
        {
            Comment p = new Comment() { Id = id };
            if (ModelState.IsValid)
            {
                await _commentiReposiory.DeleteAsync(p);
                return Json(new { isSuccess = true, msg = "删除成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "删除失败，请重试！" });
        }
        #endregion
    }
}
